package org.example.back.service.user;

import org.example.back.entity.user.UserSport;
import org.example.back.mapper.user.UserSportMapper;
import org.example.back.service.healthassistant.HealthAssistantService;
import org.example.back.service.advice.UserSportAdviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserSportService {

    @Autowired
    private UserSportMapper userSportMapper;

    @Autowired
    private HealthAssistantService healthAssistantService;

    @Autowired
    private UserSportAdviceService userSportAdviceService;

    // 插入运动记录，调用大模型生成热量
    public void addSportWithCalories(UserSport userSport) {
    if (userSport.getCalories() == null) {
        // 提前检查运动时间有效性
        if (userSport.getStartTime() == null || userSport.getEndTime() == null ||
            !userSport.getEndTime().isAfter(userSport.getStartTime())) {
            System.err.println("运动时间无效，跳过热量计算。");
            userSport.setCalories(0.0);
            userSportMapper.insertUserSport(userSport);
            return;
        }

        String prompt = String.format(
            "请根据以下用户运动数据估算其消耗的热量（单位：千卡）。请只返回纯数字，不包含单位或其他描述：运动类型：%s，开始时间：%s，结束时间：%s，运动强度：%s。",
            userSport.getSportType(),
            userSport.getStartTime(),
            userSport.getEndTime(),
            userSport.getIntensity()
        );

        try {
            String result = healthAssistantService.getAnswerFromLLM(prompt);
            System.out.println("模型原始返回: " + result);

            // 使用正则提取第一个浮点数（健壮性强于replaceAll + parse）
            Matcher matcher = Pattern.compile("(\\d+(\\.\\d+)?)").matcher(result);
            if (matcher.find()) {
                double estimatedCalories = Double.parseDouble(matcher.group(1));
                userSport.setCalories(estimatedCalories);
                System.out.println("解析出的热量为: " + estimatedCalories);
            } else {
                System.err.println("未能从模型返回中提取热量数值，将设置为0.0");
                userSport.setCalories(0.0);
            }
        } catch (Exception e) {
            System.err.println("调用大模型或解析热量失败: " + e.getMessage());
            userSport.setCalories(0.0);
        }
    }
    // 插入运动记录
    userSportMapper.insertUserSport(userSport);
    userSportAdviceService.cleanWeekAndMonthAdviceCache(userSport.getUserId());
}
    // 查询某一天的运动记录
    public List<UserSport> getUserSportByDate(Integer userId, LocalDate date) {
        return userSportMapper.findUserSportByDate(userId, date);
    }

    // 最近7天按天汇总
    public List<Map<String, Object>> getUserSportLastWeek(Integer userId) {
        return userSportMapper.findUserSportLastWeek(userId);
    }

    // 最近1个月按周汇总
    public List<Map<String, Object>> getUserSportByWeekInMonth(Integer userId) {
        return userSportMapper.findUserSportByWeekInMonth(userId);
    }

    // 删除运动记录，依据 userId + startTime 定位
    public void deleteUserSport(Integer userId, LocalDateTime startTime) {
        userSportMapper.deleteUserSportByUserIdAndStartTime(userId, startTime);
    }
}
